// UI管理文件 - 包含所有UI相关的函数

import { STATE, StateManager } from './state.js';
import { CommonUtils } from './utils.js';

// UI管理器
export const UIManager = {
    // 统一更新选择信息
    updateSelectionInfo(panelKey, count) {
        const selectors = this.getSelectionSelectors(panelKey);
        
        selectors.countElements.forEach(el => {
            if (el) el.textContent = `您选择了 ${count} 注`;
        });
        
        selectors.confirmButtons.forEach(btn => {
            if (btn) btn.disabled = count === 0;
        });
    },
    
    // 获取选择相关的DOM元素选择器
    getSelectionSelectors(panelKey) {
        const selectors = {
            countElements: [],
            confirmButtons: []
        };
        
        if (panelKey && panelKey.includes('tema-zhixuan')) {
            selectors.countElements.push(document.getElementById('selectionCount'));
            selectors.confirmButtons.push(document.getElementById('confirmSelectionBtn'));
        } else if (panelKey && panelKey.includes('zhengma')) {
            const subType = panelKey.split('-')[1];
            const countId = subType === 'renxuan' ? 'zhengmaSelectionCount' : `${subType}SelectionCount`;
            const btnId = subType === 'renxuan' ? 'zhengmaConfirmBtn' : `${subType}ConfirmBtn`;
            
            selectors.countElements.push(document.getElementById(countId));
            selectors.confirmButtons.push(document.getElementById(btnId));
        } else if (panelKey && panelKey.includes('lianma')) {
            // 处理连码玩法
            const subType = panelKey.split('-')[1];
            const countId = `${subType}SelectionCount`;
            const btnId = `${subType}ConfirmBtn`;
            
            selectors.countElements.push(document.getElementById(countId));
            selectors.confirmButtons.push(document.getElementById(btnId));
        } else if (panelKey && panelKey.includes('banbo')) {
            // 处理半波玩法
            selectors.countElements.push(document.getElementById('banboSelectionCount'));
            selectors.confirmButtons.push(document.getElementById('banboConfirmBtn'));
        } else if (panelKey && panelKey.includes('shengxiao')) {
            // 处理生肖玩法
            const subType = panelKey.split('-')[1];
            const countId = `${subType}SelectionCount`;
            const btnId = `${subType}ConfirmBtn`;
            
            selectors.countElements.push(document.getElementById(countId));
            selectors.confirmButtons.push(document.getElementById(btnId));
        } else if (panelKey && panelKey.includes('buzhong')) {
            // 处理不中玩法
            const subType = panelKey.split('-')[1];
            const countId = `${subType}SelectionCount`;
            const btnId = `${subType}ConfirmBtn`;
            
            selectors.countElements.push(document.getElementById(countId));
            selectors.confirmButtons.push(document.getElementById(btnId));
        } else if (panelKey && panelKey.includes('sebo')) {
            // 处理色波玩法
            const subType = panelKey.split('-')[1];
            const countId = `${subType}SelectionCount`;
            const btnId = `${subType}ConfirmBtn`;
            
            selectors.countElements.push(document.getElementById(countId));
            selectors.confirmButtons.push(document.getElementById(btnId));
        }
        
        return selectors;
    },
    
    // 统一面板切换逻辑
    switchPanel(targetPanelKey) {
        // 隐藏所有面板
        document.querySelectorAll('.content-panel').forEach(panel => {
            panel.classList.remove('active');
        });
        
        // 显示目标面板
        const targetPanel = document.querySelector(`.content-panel.${targetPanelKey}`);
        
        if (targetPanel) {
            targetPanel.classList.add('active');
            this.setupPanelContent(targetPanelKey, targetPanel);
        }
    },
    
    // 设置面板内容
    setupPanelContent(panelKey, panel) {
        const [game, sub] = panelKey.split('-');
        
        // 简化逻辑，直接判断是否需要设置号码面板
        if (sub === 'zhixuan' || sub === 'renxuan' || sub.includes('te') || 
            game === 'lianma' || game === 'buzhong') {
            this.setupNumberPanel(panel, panelKey);
        }
    },
    
    // 设置号码面板
    setupNumberPanel(panel, panelKey) {
        const numberGrid = panel.querySelector('.number-grid');
        
        // 由于app.js已经生成了所有号码按钮，这里只需要确保面板正确显示
        // 不再重复生成按钮，避免冲突
        if (!numberGrid) return;
        
        // 如果没有按钮，说明初始化有问题，重新生成
        if (numberGrid.children.length === 0) {
            for (let i = 1; i <= 49; i++) {
                const button = document.createElement('button');
                button.className = `number-btn ${CommonUtils.getNumberColor(i)}`;
                button.textContent = CommonUtils.formatNumber(i);
                button.dataset.number = i;
                button.dataset.panel = panelKey;
                numberGrid.appendChild(button);
            }
        }
    },
    
    // 统一页签切换逻辑
    switchTab(tabs, activeTab, dataAttribute, callback) {
        // 移除所有活动状态
        tabs.forEach(tab => tab.classList.remove('active'));
        
        // 设置当前活动状态
        activeTab.classList.add('active');
        
        // 执行回调
        if (callback) {
            const dataValue = activeTab.getAttribute(dataAttribute);
            callback(dataValue);
        }
    },
    
    // 清空所有选择状态
    clearAllSelections() {
        // 清空号码选择
        StateManager.clearSelectedNumbers();
        document.querySelectorAll('.number-btn.selected').forEach(btn => {
            btn.classList.remove('selected');
        });
        
        // 清空两面选择
        document.querySelectorAll('.side-btn.selected').forEach(btn => {
            btn.classList.remove('selected');
        });
        
        // 清空半波选择
        document.querySelectorAll('.banbo-btn-detailed.selected').forEach(btn => {
            btn.classList.remove('selected');
        });
        
        // 清空生肖选择
        this.clearAnimalSelections();
        
        // 清空总肖选择
        document.querySelectorAll('.zongxiao-btn.selected').forEach(btn => {
            btn.classList.remove('selected');
        });
        
        // 清空尾数选择
        this.clearTailSelections();
        
        // 清空色波选择
        this.clearSeboSelections();
        
        // 更新选择信息
        const panelKey = `${STATE.currentGame}-${STATE.currentSub}`;
        this.updateSelectionInfo(panelKey, 0);
    },

    // 清空生肖选择状态
    clearAnimalSelections() {
        StateManager.clearSelectedAnimals();
        document.querySelectorAll('.animal-btn.selected').forEach(btn => {
            btn.classList.remove('selected');
        });
    },

    // 清空尾数选择状态
    clearTailSelections() {
        StateManager.clearSelectedTails();
        StateManager.clearSelectedHeads();
        document.querySelectorAll('.tail-btn.selected').forEach(btn => {
            btn.classList.remove('selected');
        });
    },

    // 清空色波选择状态
    clearSeboSelections() {
        document.querySelectorAll('.sebo-btn.selected').forEach(btn => {
            btn.classList.remove('selected');
        });
    },
    
    // 统一模态框显示
    showModal(modalId, data) {
        const modal = document.getElementById(modalId);
        if (!modal) return;
        
        if (data) {
            this.updateModalContent(modalId, data);
        }
        
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    },
    
    // 统一模态框隐藏
    hideModal(modalId) {
        const modal = document.getElementById(modalId);
        if (!modal) return;
        
        modal.classList.remove('active');
        document.body.style.overflow = 'auto';
    },
    
    // 更新模态框内容
    updateModalContent(modalId, data) {
        const modal = document.getElementById(modalId);
        if (!modal) return;
        
        if (modalId === 'confirmModal' && data.betList) {
            // 更新投注详情列表
            const detailsList = modal.querySelector('#detailsList');
            if (detailsList) {
                detailsList.innerHTML = data.betList.map(bet => {
                    const odds = bet.customOdds || bet.odds || 1;
                    const potentialWin = window.PayoutCalculator.calculatePotentialPayout(bet);
                    return `<div class="detail-item">
                        <div>${bet.description}</div>
                        <div style="font-size: 12px; color: #666; margin-top: 2px;">
                            ${bet.count}注 × ¥${bet.amount} × ${odds} = ¥${potentialWin.toFixed(2)}
                        </div>
                    </div>`;
                }).join('');
            }
            
            // 更新总金额
            const modalTotalAmount = modal.querySelector('#modalTotalAmount');
            if (modalTotalAmount) {
                modalTotalAmount.textContent = data.totalAmount;
            }
        }
    },
    
    // 生成号码网格
    generateNumberGrid() {
        const numberGrids = document.querySelectorAll('.number-grid');
        
        numberGrids.forEach(grid => {
            grid.innerHTML = '';
            
            for (let i = 1; i <= 49; i++) {
                const button = document.createElement('button');
                button.className = `number-btn ${CommonUtils.getNumberColor(i)}`;
                button.setAttribute('data-number', i);
                button.textContent = CommonUtils.formatNumber(i);
                grid.appendChild(button);
            }
        });
    },
    
    // 创建投注项目元素
    createBetItemElement(bet) {
        const div = document.createElement('div');
        div.className = 'bet-item';
        div.setAttribute('data-bet-id', bet.id);
        
        const potentialWin = window.PayoutCalculator.calculatePotentialPayout(bet);
        const currentOdds = bet.customOdds || bet.odds || 1;
        
        div.innerHTML = `
            <div class="bet-info">
                <span class="bet-type">${bet.description}</span>
                <span class="bet-count">总共 ${bet.count} 注</span>
            </div>
            <div class="bet-amount">
                <span>每注</span>
                <input type="number" value="${bet.amount}" min="1" class="bet-amount">
                <span>元</span>
            </div>
            <div class="bet-odds">
                <span>赔率</span>
                <input type="number" value="${currentOdds}" min="0.1" step="0.001" class="bet-odds">
                <button type="button" class="odds-history-btn" title="历史赔率">⏰</button>
            </div>
            <div class="bet-potential">
                <span>${window.PayoutCalculator.getPotentialPayoutLabel(bet)}：<span class="potential-amount">${potentialWin.toFixed(2)}元</span></span>
            </div>
            <button class="delete-bet">删除</button>
        `;
        
        return div;
    },
    
    // 显示赔率历史下拉框
    showOddsHistoryDropdown(button) {
        // 先关闭其他下拉框
        document.querySelectorAll('.odds-history-dropdown').forEach(dropdown => {
            dropdown.remove();
        });
        
        const betItem = button.closest('.bet-item');
        const betId = betItem.getAttribute('data-bet-id');
        const bet = STATE.betList.find(b => b.id == betId);
        
        if (!bet || !bet.gameTypeKey) return;
        
        const oddsHistory = StateManager.getOddsHistory(bet.gameTypeKey);
        
        if (oddsHistory.length === 0) {
            // 显示提示信息
            const tooltip = document.createElement('div');
            tooltip.className = 'odds-history-dropdown';
            tooltip.innerHTML = '<div class="odds-history-item" style="color: #6c757d;">暂无历史赔率</div>';
            
            const betOdds = button.closest('.bet-odds');
            betOdds.appendChild(tooltip);
            
            // 3秒后自动消失
            setTimeout(() => {
                tooltip.remove();
            }, 3000);
            return;
        }
        
        // 创建下拉框
        const dropdown = document.createElement('div');
        dropdown.className = 'odds-history-dropdown';
        
        // 添加标题显示投注类型
        const title = document.createElement('div');
        title.className = 'odds-history-title';
        title.textContent = CommonUtils.getGameTypeDisplayName(bet.gameTypeKey);
        title.style.cssText = 'padding: 6px 12px; font-size: 11px; color: #6c757d; border-bottom: 1px solid #e9ecef; font-weight: bold;';
        dropdown.appendChild(title);
        
        // 添加历史赔率选项
        oddsHistory.forEach((odds, index) => {
            const item = document.createElement('div');
            item.className = 'odds-history-item';
            
            // 显示赔率和使用次序信息
            const oddsText = odds.toFixed(3);
            if (index === 0) {
                item.innerHTML = `<span style="font-weight: bold;">${oddsText}</span> <small style="color: #28a745;">最近</small>`;
            } else {
                item.textContent = oddsText;
            }
            
            item.addEventListener('click', function() {
                // 应用选中的赔率
                const oddsInput = betItem.querySelector('.bet-odds');
                if (oddsInput) {
                    oddsInput.value = odds;
                    // 触发input事件以更新相关数据
                    oddsInput.dispatchEvent(new Event('input', { bubbles: true }));
                }
                dropdown.remove();
            });
            
            dropdown.appendChild(item);
        });
        
        // 添加到DOM
        const betOdds = button.closest('.bet-odds');
        betOdds.appendChild(dropdown);
        
        // 点击其他地方关闭下拉框
        setTimeout(() => {
            document.addEventListener('click', function closeDropdown(e) {
                if (!dropdown.contains(e.target) && e.target !== button) {
                    dropdown.remove();
                    document.removeEventListener('click', closeDropdown);
                }
            });
        }, 100);
    }
}; 